package com.jic.product.controller.rest;

import com.alibaba.fastjson.JSONArray;
import com.jic.common.base.vo.Page;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.common.redis.RedisClientTemplate;
import com.jic.conf.request.rest.UpdateProductCommentRequest;
import com.jic.enums.RedisKey;
import com.jic.member.api.rest.MememberApi;
import com.jic.member.response.MemberResponse;
import com.jic.member.response.MememberUserResponse;
import com.jic.product.constant.consist.ResponseCode;
import com.jic.product.controller.rest.request.MProductCommentRestRequest;
import com.jic.product.controller.rest.vo.MProductCommentCountVo;
import com.jic.product.controller.rest.vo.MProductCommentInfoVo;
import com.jic.product.controller.rest.vo.MProductCommentVo;
import com.jic.product.entity.Product;
import com.jic.product.exception.AppRuntimeException;
import com.jic.product.manage.response.ProductResponse;
import com.jic.product.model.entity.File;
import com.jic.product.model.entity.ProductComment;
import com.jic.product.model.entity.ProductCommentReply;
import com.jic.product.rest.response.ProductPropertyResponse;
import com.jic.product.service.FileService;
import com.jic.product.service.ProductCommentReplyService;
import com.jic.product.service.ProductCommentService;
import com.jic.product.service.ProductService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * @author: hwq
 * @date: 2020-01-09
 * @remark: BBC接口 商品评论接口
 */
@Slf4j
@Api(tags = "API-评价")
@RestController
@RequestMapping("/apiProductComment")
public class ApiProductCommentController {

    @Autowired
    RedisClientTemplate redisClientTemplate;

    @Autowired
    private ProductCommentService productCommentService;
    @Autowired
    private FileService fileService;

    @Autowired
    private ProductCommentReplyService productCommentReplyService;

    @Autowired
    private ProductService productService;

    @Autowired
    private MememberApi mememberApi;




    @ApiOperation("发表评论/追评")
    @ResponseBody
    @PostMapping("updateProductComment")
    public RestResult<String> updateProductComment(@RequestBody UpdateProductCommentRequest updateProductComment) {
        RestResult<String> success = productCommentService.updateProductComment(updateProductComment);
        return success;
    }

    @ApiOperation("商品详情中评论列表查询")
    @ResponseBody
    @PostMapping("queryProductCommentListPage")
    public RestResult<PageResult<MProductCommentVo>> queryProductCommentListPage(@RequestBody MProductCommentRestRequest request) {
        try {
            //获取到前端换的商品id，查询出系列子品的id
            List<Long> productIds = new ArrayList<>();
            productIds.add(request.getProductId());
            Product product = new Product();
            product.setParentId(request.getProductId());
            List<Product> list = productService.queryProductInfoByParentId(product);
            list.forEach(product1 -> {
                productIds.add(product1.getId());
            });
            Page page = new Page();
            page.setLimit(request.getLimit());
            page.setStart(request.getStart());
            ProductComment productComment = new ProductComment();
            BeanUtils.copyProperties(request, productComment);
            productComment.setProductIds(productIds);
            PageResult<ProductComment> productCommentPageResult = productCommentService.queryPage(productComment, page);
            List<ProductComment> productCommentResponses = productCommentPageResult.getRows();
            List<MProductCommentVo> res = new ArrayList<>();
            productCommentResponses.forEach(productCommentResponse -> {
                MProductCommentVo mProductCommentVo = new MProductCommentVo();
                BeanUtils.copyProperties(productCommentResponse, mProductCommentVo);
                //查询初次评论中的商品属性规格
                Long productId = productCommentResponse.getProductId();
                List<ProductPropertyResponse> productPropertyResponsesList = productService.queryPropertyNameByProductId(productId);
                mProductCommentVo.setProductPropertyResponseList(productPropertyResponsesList);
                //初次评论查询图片
                List<File> fileList = fileService.query(new File() {{
                    setType(0);
                    setBusinessId(productCommentResponse.getId());
                }});
                mProductCommentVo.setFileList(fileList);//初次评论评论图片
                //初次评论的回复查询
                ProductCommentReply productCommentReply = new ProductCommentReply();
                productCommentReply.setCommentId(productCommentResponse.getId());
                List<ProductCommentReply> productCommentReplyList = productCommentReplyService.query(productCommentReply);
                mProductCommentVo.setWriteBackList(productCommentReplyList);
                //查询追评
                ProductComment productComment1 = new ProductComment();
                productComment1.setPid(productCommentResponse.getId());
                productComment1.setType(2);
                List<ProductComment> additionalReviewList = productCommentService.query(productComment1);
                List<MProductCommentVo> additionalReviewRes = new ArrayList<>();//追评
                //查询追评图片
                additionalReviewList.forEach(additionalReviewInfo -> {
                    MProductCommentVo additionalReviewVo = new MProductCommentVo();
                    //查询追评图片
                    List<File> additionalReviewFileList = fileService.query(new File() {{
                        setType(0);
                        setBusinessId(additionalReviewInfo.getId());
                    }});
                    try {
                        BeanUtils.copyProperties(additionalReviewInfo, additionalReviewVo);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    additionalReviewVo.setFileList(additionalReviewFileList);
                    //查询追评的回复
                    ProductCommentReply productCommentReply1 = new ProductCommentReply();
                    productCommentReply1.setCommentId(additionalReviewInfo.getId());
                    List<ProductCommentReply> productCommentReplyList1 = productCommentReplyService.query(productCommentReply1);
                    additionalReviewVo.setWriteBackList(productCommentReplyList1);
                    additionalReviewRes.add(additionalReviewVo);
                });
                mProductCommentVo.setAdditionalReviewList(additionalReviewRes);//追评内容
                //评价人信息
                MemberResponse memberResponse=new MemberResponse();
                RestResult<MememberUserResponse> mememberUserResponseRestResult = mememberApi.queryMemberUserInfo(productCommentResponse.getMemberId());
                if(null!=mememberUserResponseRestResult &&null!=mememberUserResponseRestResult.getData()){
                    memberResponse.setHeadPicUrl(mememberUserResponseRestResult.getData().getHeadImage());
                    memberResponse.setUsername(mememberUserResponseRestResult.getData().getNickName());
                }
                mProductCommentVo.setMemberResponse(memberResponse);
                res.add(mProductCommentVo);
            });
            return RestResult.success(new PageResult<MProductCommentVo>() {{
                setRows(res);
                setTotal(productCommentPageResult.getTotal());
            }});
        } catch (Exception e) {
            log.error("商品评论分页查询异常", e);
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "`商品评论分页查询异常");
        }
    }

    /**
     * BBC接口 统计商品详情中好评/中评/差评等数据
     * 根据商品id统计
     *
     * @return
     */
    @ApiOperation(value = "统计商品详情中/全部/好评/中评/差评/有图/等数据")
    @ResponseBody
    @PostMapping("/queryCommentCount")
    public RestResult<MProductCommentCountVo> queryCommentCount(@RequestBody MProductCommentRestRequest request) {
        try {
            ProductComment productComment = new ProductComment();
            MProductCommentCountVo mProductCommentCountVo = new MProductCommentCountVo();
            Product product = productService.queryByPrimaryKey(request.getProductId());
            if (null != product) {
                if (product.getTypeOfProduct() == 1) {
                    List<Long> list = new ArrayList<Long>();
                    list.add(request.getProductId());
                    productComment.setProductIds(list);
                } else {
                    Product product1 = new Product();
                    product1.setParentId(request.getProductId());
                    List<Product> productList = productService.query(product1);
                    List<Long> list = new ArrayList<Long>();
                    productList.forEach(item -> {
                        list.add(item.getId());
                    });
                    if (CollectionUtils.isNotEmpty(list)) {
                        productComment.setProductIds(list);
                    } else {
                        return RestResult.success(mProductCommentCountVo);
                    }
                }
            } else {
                return RestResult.error("9999", "商品不存在");
            }
            productComment.setType(1);
            //商品全部评论数量
            long allCount = productCommentService.queryCount(productComment);
            //商品带图数量
            //根据评论id查询是否存在图片--先查询出所有初次评论--暂不统计追评有图片的数据
            List<ProductComment> list = productCommentService.query(productComment);
            List<ProductComment> haveImgList = new ArrayList<>();
            list.forEach(productComment1 -> {
                List<File> FileList = fileService.query(new File() {{
                    setType(0);
                    setBusinessId(productComment1.getId());
                }});
                if (FileList.size() > 0) {
                    haveImgList.add(productComment1);
                }
            });
            long haveImgCount = haveImgList.size();

            //商品好评数量
            productComment.setStarNumStart(4);
            productComment.setStarNumEnd(5);
            long goodCount = productCommentService.queryCount(productComment);
            //商品中评数量
            productComment.setStarNumStart(3);
            productComment.setStarNumEnd(3);
            long mediumCount = productCommentService.queryCount(productComment);
            //商品差评数量
            productComment.setStarNumStart(0);
            productComment.setStarNumEnd(2);
            long badCount = productCommentService.queryCount(productComment);

            mProductCommentCountVo.setAllCount(allCount);
            mProductCommentCountVo.setGoodCount(goodCount);
            mProductCommentCountVo.setMediumCount(mediumCount);
            mProductCommentCountVo.setBadCount(badCount);
            mProductCommentCountVo.setHaveImgCount(haveImgCount);

            return RestResult.success(mProductCommentCountVo);
        } catch (Exception e) {
            log.error("异常", e);
            throw new AppRuntimeException(ResponseCode.EXCEPTION);
        }
    }

    @ApiOperation("商品详情中评论列表查询--有图")
    @ResponseBody
    @PostMapping("queryProductCommentHaveImgListPage")
    public RestResult<PageResult<MProductCommentVo>> queryProductCommentHaveImgListPage(@RequestBody MProductCommentRestRequest request) {
        try {
            //获取到前端换的商品id，查询出系列子品的id
            List<Long> productIds = new ArrayList<>();
            productIds.add(request.getProductId());
            Product product = new Product();
            product.setParentId(request.getProductId());
            List<Product> list = productService.query(product);
            list.forEach(product1 -> {
                productIds.add(product1.getId());
            });
            Page page = new Page();
            page.setLimit(request.getLimit());
            page.setStart(request.getStart());
            ProductComment productComment = new ProductComment();
            BeanUtils.copyProperties(request, productComment);
            productComment.setType(1);
            productComment.setProductIds(productIds);
            PageResult<ProductComment> productCommentPageResult = productCommentService.queryHaveImgPage(productComment, page);
            List<ProductComment> productCommentResponses = productCommentPageResult.getRows();
            List<MProductCommentVo> res = new ArrayList<>();
            productCommentResponses.forEach(productCommentResponse -> {
                MProductCommentVo mProductCommentVo = new MProductCommentVo();
                //查询初次评论中的商品属性规格
                Long productId = productCommentResponse.getProductId();
                List<ProductPropertyResponse> productPropertyResponsesList = productService.queryPropertyNameByProductId(productId);
                mProductCommentVo.setProductPropertyResponseList(productPropertyResponsesList);
                //初次评论查询图片
                List<File> fileList = fileService.query(new File() {{
                    setType(0);
                    setBusinessId(productCommentResponse.getId());
                }});
                try {
                    BeanUtils.copyProperties(productCommentResponse, mProductCommentVo);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                mProductCommentVo.setFileList(fileList);//初次评论评论图片
                //初次评论的回复查询
                ProductCommentReply productCommentReply = new ProductCommentReply();
                productCommentReply.setCommentId(productCommentResponse.getId());
                List<ProductCommentReply> productCommentReplyList = productCommentReplyService.query(productCommentReply);
                mProductCommentVo.setWriteBackList(productCommentReplyList);
                //查询追评
                ProductComment productComment1 = new ProductComment();
                productComment1.setPid(productCommentResponse.getId());
                productComment1.setType(2);
                List<ProductComment> additionalReviewList = productCommentService.query(productComment1);
                List<MProductCommentVo> additionalReviewRes = new ArrayList<>();//追评
                additionalReviewList.forEach(additionalReviewInfo -> {
                    MProductCommentVo additionalReviewVo = new MProductCommentVo();
                    //查询追评图片
                    List<File> additionalReviewFileList = fileService.query(new File() {{
                        setType(0);
                        setBusinessId(additionalReviewInfo.getId());
                    }});
                    try {
                        BeanUtils.copyProperties(additionalReviewInfo, additionalReviewVo);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    additionalReviewVo.setFileList(additionalReviewFileList);
                    //查询追评的回复
                    ProductCommentReply productCommentReply1 = new ProductCommentReply();
                    productCommentReply1.setCommentId(additionalReviewInfo.getId());
                    List<ProductCommentReply> productCommentReplyList1 = productCommentReplyService.query(productCommentReply1);
                    additionalReviewVo.setWriteBackList(productCommentReplyList1);
                    additionalReviewRes.add(additionalReviewVo);
                });
                mProductCommentVo.setAdditionalReviewList(additionalReviewRes);//追评内容
                res.add(mProductCommentVo);
            });
            return RestResult.success(new PageResult<MProductCommentVo>() {{
                setRows(res);
                setTotal(productCommentPageResult.getTotal());
            }});
        } catch (Exception e) {
            log.error("商品评论分页查询异常", e);
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "`商品评论分页查询异常");
        }
    }


    /**
     * BBC接口 商品详情中评论详情
     * 根据评论id查询
     *
     * @return
     */
    @ApiOperation(value = "商品详情中评论详情")
    @ResponseBody
    @PostMapping("/getCommentInfo")
    public RestResult<MProductCommentInfoVo> getCommentInfo(@RequestBody MProductCommentRestRequest request) {
        try {
            String memStr = redisClientTemplate.get(RedisKey.H5_LOGIN_TOKEN_.getName() + request.getToken());
            Map memMap = JSONArray.parseObject(memStr, Map.class);
            MProductCommentInfoVo mProductCommentInfoVo = new MProductCommentInfoVo();
            ProductComment query = new ProductComment();
            query.setMemberId(Long.valueOf(memMap.get("id").toString()));
            query.setProductId(request.getProductId());
            query.setOrderNo(request.getOrderNo());
            List<ProductComment> query1 = productCommentService.query(query);
            ProductComment productComment = query1.get(0);
            ProductResponse productResponse = productService.queryProductInfo(productComment.getProductId());
            if (null != productResponse) {
                mProductCommentInfoVo.setProductImg(productResponse.getPictureUrl());
            }

            try {
                BeanUtils.copyProperties(productComment, mProductCommentInfoVo);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (productComment != null) {
                //查询图片
                List<File> fileList = fileService.query(new File() {{
                    setType(0);
                    setBusinessId(productComment.getId());
                }});
                mProductCommentInfoVo.setFileList(fileList);
                //初次评论的回复查询
                ProductCommentReply productCommentReply = new ProductCommentReply();
                productCommentReply.setCommentId(productComment.getId());
                List<ProductCommentReply> productCommentReplyList = productCommentReplyService.query(productCommentReply);
                mProductCommentInfoVo.setWriteBackList(productCommentReplyList);
                //查询追评
                ProductComment productComment1 = new ProductComment();
                productComment1.setPid(productComment.getId());
                productComment1.setType(2);
                List<ProductComment> additionalReviewList = productCommentService.query(productComment1);
                List<MProductCommentInfoVo> additionalReviewList1 = new ArrayList<>();//追评
                //查询追评图片
                additionalReviewList.forEach(additionalReviewInfo -> {
                    MProductCommentInfoVo ProductComment = new MProductCommentInfoVo();
                    //查询追评图片
                    List<File> additionalReviewFileList = fileService.query(new File() {{
                        setType(0);
                        setBusinessId(additionalReviewInfo.getId());
                    }});
                    try {
                        BeanUtils.copyProperties(additionalReviewInfo, ProductComment);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    ProductComment.setFileList(additionalReviewFileList);
                    //查询追评的回复
                    ProductCommentReply productCommentReply1 = new ProductCommentReply();
                    productCommentReply1.setCommentId(additionalReviewInfo.getId());
                    List<ProductCommentReply> productCommentReplyList1 = productCommentReplyService.query(productCommentReply1);
                    ProductComment.setWriteBackList(productCommentReplyList1);
                    additionalReviewList1.add(ProductComment);
                });
                mProductCommentInfoVo.setAdditionalReviewList(additionalReviewList1);
            }
            return RestResult.success(mProductCommentInfoVo);
        } catch (Exception e) {
            log.error("异常", e);
            throw new AppRuntimeException(ResponseCode.EXCEPTION);
        }
    }


}
